"""
read_email.py
每隔半小时读取邮箱内容，拿到最新一封监控邮件，如果是新邮件，则获得附件，并解压zip
"""
import zmail
import datetime
import zipfile
import time
import os

EMAIL_NAME = '1300945503@qq.com'
EMAIL_PSSWD = '*************'
EAMIL_SUBJECT = 'Data Monitor'
DOWNLOAD_FILE_PATH = '/root/for_monitor'
UNZIP_FILENAME = 'for_monitor.zip'
UNZIP_FILE_PATH = "/root"
RECORD_PATH = "/root/for_monitor/download_record.txt"


def download_email_time():
    server = zmail.server(EMAIL_NAME, EMAIL_PSSWD)
    # 获得subject为 Data Monitor 的邮件集合
    mail = server.get_mails(subject=EAMIL_SUBJECT)
    # 读取最新一封邮件的部分内容
    email_time = mail[-1]['content_text'][0]
    return email_time[-19:], mail[-1]


def download_email(mail):
    # 读取附件  邮件 存放路径  如果有同名文件则覆盖
    zmail.save_attachment(mail, target_path=DOWNLOAD_FILE_PATH, overwrite=True)


def unzip_csv():
    zip_file = zipfile.ZipFile(DOWNLOAD_FILE_PATH + '/' + UNZIP_FILENAME)
    zip_list = zip_file.namelist()  # 得到压缩包里所有文件
    for f in zip_list:
        zip_file.extract(f, UNZIP_FILE_PATH)  # 循环解压文件到指定目录
    zip_file.close()  # 关闭文件，必须有，释放内存


def sleeptime(hours, minutes, seconds):
    """
    定义程序间隔时间
    :param hours: 需要间隔的小时数
    :param minutes: 需要间隔的分钟数
    :param seconds: 需要间隔的秒数
    :return: 总秒数
    """
    return hours * 3600 + minutes * 60 + seconds


def record(flag, msg):
    """
    将结果记录到文件中，没有文件则创建文件
    :param flag: 1表示下载成功，0表示下载失败
    :param msg: 报错信息
    :return: 没有返回值
    """
    if os.path.exists(RECORD_PATH):
        with open(RECORD_PATH, 'a+') as f:
            if flag == 1:
                f.write('文件下载解压成功...%s' % datetime.datetime.now() + '\r\n')
            elif flag == 0:
                f.write('文件下载解压失败...%s' % datetime.datetime.now() + '  ' + repr(msg) + '\r\n')
    else:
        f = open(RECORD_PATH, 'w', encoding="utf-8")
        f.close()


if __name__ == '__main__':
    seconds = sleeptime(0, 30, 0)
    time_dict = {}
    while True:
        try:
            email_time, mail = download_email_time()
            if email_time not in time_dict:
                time_dict[email_time] = datetime.datetime.now()
                download_email(mail)
                unzip_csv()
                record(1, '')
            else:
                pass
        except Exception as e:
            record(0, e)
        print('循环中...%s'%datetime.datetime.now()+'\r\n')
        time.sleep(seconds)
